﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.Common;
using Casamiel.Common.Extensions;
using Casamiel.Domain;
using Casamiel.Domain.Request;
using Casamiel.Domain.Response;
using Casamiel.Domain.Response.IC;
using MediatR;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;

namespace Casamiel.Application.Commands
{
	/// <summary>
	/// 
	/// </summary>
	public sealed class GetTicketsStatusByOrderCommandHandler:BaseCommandHandler,IRequestHandler<GetTicketsStatusByOrderCommand, BaseResult<List<TicketItem>>>
	{
		private readonly IMbrStoreRepository _mbrStoreRepository;
		private readonly IMemberCardRepository _memberCardRepository;

		public GetTicketsStatusByOrderCommandHandler(INetICService netICService, IHttpClientFactory httpClientFactory, IOptionsSnapshot<CasamielSettings> settings,
		IMbrStoreRepository mbrStoreRepository, IMemberCardRepository memberCardRepository) : base(netICService, httpClientFactory, settings)
		{
			_mbrStoreRepository = mbrStoreRepository;
			_memberCardRepository = memberCardRepository;
			 
		}
	 
		/// <summary>
		/// 
		/// </summary>
		/// <param name="request"></param>
		/// <param name="cancellationToken"></param>
		/// <returns></returns>
		public async Task<BaseResult<List<TicketItem>>> Handle(GetTicketsStatusByOrderCommand request, CancellationToken cancellationToken)
		{
			if (request is null) {
				throw new ArgumentNullException(nameof(request));
			}
			if (request.GoodsList==null) {
				return new BaseResult<List<TicketItem>>(null, 9999, "没有选用任何产品");
			}
			var cardInfo = await _memberCardRepository.GetBindCardAsync<ICasaMielSession>(request.Mobile).ConfigureAwait(false);
			if (cardInfo == null) {
				return new BaseResult<List<TicketItem>>(new List<TicketItem>(), 0, "");
			}
			var req = new GetTicticketReq { Cardno = cardInfo.CardNO, State = 2, Pageindex = 1, Pagesize = 30 };
			var a = await NetICService.Geticticket(req).ConfigureAwait(false);

			var list = JsonConvert.DeserializeObject<TicketItemRoot>(a.content);
			if (request.Mobile == "18702733027") {
				OrderLogger.Trace($"GetTicticketR:{JsonConvert.SerializeObject(list)}");
			}
			 var OrderAmount = request.GoodsList.Sum(c => c.GoodsQuantity * c.Price);
			var storeInfo = await _mbrStoreRepository.GetByStoreIdAsync<ICasaMielSession>(request.StoreId).ConfigureAwait(false);
			if (storeInfo == null) {
				return new BaseResult<List<TicketItem>>(new List<TicketItem>(), 0, "");
			}
			List<long> ids = new List<long>();
			if (list != null) {
				foreach (var item in list.Tickets) {
					if (ids.Contains(item.Productid)) {
						continue;
					}
					ids.Add(item.Productid);
				}
			}
			
			if (ids.Any()) {
				var ticketLimit = await NetICService.TicketLimit(storeInfo.RelationId, ids, 0, true).ConfigureAwait(false);
				var rule = JsonConvert.DeserializeObject<TicketsRules>(ticketLimit.content);


				Console.WriteLine(JsonConvert.SerializeObject(ticketLimit));
				var count = list.Tickets.Count;
				if (count > 0) {

					Parallel.For(0, count, (i) => {
						var list216 = rule.Tickets.Where(c => c.Limittype == 216 && c.Productid == list.Tickets[i].Productid);
						if (list216.Any()) {
							bool s = false;
							var list216msg = "";
							foreach (var item in list216) {
								var ss = request.GoodsList.Count(c => c.GoodsRelationId == int.Parse(item.Limitvalue, System.Globalization.CultureInfo.CurrentCulture));
								if (ss > 0) {
									s = true;
								} else {
									list216msg += $"{item.Productname}{item.Limitdesc}";
								}
							}
							if (!s) {
								list.Tickets[i].State = 0;
							}
						}

						var list215 = rule.Tickets.Where(c => c.Limittype == 215 && c.Productid == list.Tickets[i].Productid);
						if (list215.Any()) {
							var list215sucess = true;
							var amsg = "";
							foreach (var item in list215) {
								if (!request.GoodsList.Any(c => c.GoodsRelationId == int.Parse(item.Limitvalue, System.Globalization.CultureInfo.CurrentCulture))) {
									amsg += $"{item.Productname}{item.Limitdesc}";
									list215sucess = false;
								}
							}
							if (!list215sucess) {
								list.Tickets[i].State = 0;
							}

						}
						var abc = rule.Tickets.Where(c => c.Productid == list.Tickets[i].Productid).ToList();
						foreach (var item in abc) {
							if (item.Limittype == 51) {
								var tamount = OrderAmount;
								 
								if (DateTime.Now.Month >= 7 && request.IsTakeOut) {
									if (OrderAmount >= 40) {
										tamount -= 5;
									}
								}
								if (OrderAmount < item.Limitvalue.ToDecimal(0)) {
									list.Tickets[i].State = 0;
								}
							}
							if (item.Limittype == 21) {
								var aa = request.GoodsList.Count(c => c.GoodsRelationId == int.Parse(item.Limitvalue, System.Globalization.CultureInfo.CurrentCulture));
								if (aa < 1) {
									list.Tickets[i].State = 0;
								}
							}
							if (item.Limittype == 22) {
								var aa = request.GoodsList.Count(c => c.GoodsRelationId == int.Parse(item.Limitvalue, System.Globalization.CultureInfo.CurrentCulture));
								if (aa > 0) {
									list.Tickets[i].State = 0;
								}
							}
						}
					});
					var content = list.Tickets.OrderByDescending(c => c.State).ToList();
					return new BaseResult<List<TicketItem>>(content, 0, "");
				}
			}
			return new BaseResult<List<TicketItem>>(new List<TicketItem>(), 0, "");
		}
	}
}
